import tkinter as tk
from tkinter import ttk, messagebox
import sqlite3
from datetime import datetime


class MembershipSystem:
    def __init__(self, root):
        self.root = root
        self.root.title("理发店会员管理系统1.0")

        # 初始化数据库
        self.conn = sqlite3.connect('barbershop.db')
        self.create_tables()

        # 创建界面
        self.create_widgets()
        self.load_members()

    def create_tables(self):
        """创建数据库表结构"""
        cursor = self.conn.cursor()
        # 会员信息表
        cursor.execute('''CREATE TABLE IF NOT EXISTS members (
                        id INTEGER PRIMARY KEY AUTOINCREMENT,
                        name TEXT NOT NULL,
                        phone TEXT UNIQUE NOT NULL,
                        balance REAL DEFAULT 0,
                        points INTEGER DEFAULT 0,
                        reg_date TEXT)''')
        # 交易记录表
        cursor.execute('''CREATE TABLE IF NOT EXISTS transactions (
                        id INTEGER PRIMARY KEY AUTOINCREMENT,
                        member_id INTEGER,
                        amount REAL,
                        type TEXT,
                        description TEXT,
                        date TEXT)''')
        self.conn.commit()

    def create_widgets(self):
        """创建主界面组件"""
        # 搜索区域
        search_frame = ttk.Frame(self.root)
        search_frame.pack(pady=10)

        ttk.Label(search_frame, text="搜索会员:").grid(row=0, column=0)
        self.search_entry = ttk.Entry(search_frame, width=30)
        self.search_entry.grid(row=0, column=1, padx=5)
        self.search_entry.bind('<KeyRelease>', self.search_member)

        # 会员列表
        self.tree = ttk.Treeview(self.root, columns=('ID', 'Name', 'Phone', 'Balance'), show='headings')
        self.tree.heading('ID', text='会员ID')
        self.tree.heading('Name', text='姓名')
        self.tree.heading('Phone', text='电话')
        self.tree.heading('Balance', text='余额')
        self.tree.pack(fill=tk.BOTH, expand=True)

        # 操作按钮
        btn_frame = ttk.Frame(self.root)
        btn_frame.pack(pady=10)

        ttk.Button(btn_frame, text="添加会员", command=self.show_add_member).grid(row=0, column=0, padx=5)
        ttk.Button(btn_frame, text="充值", command=self.show_recharge).grid(row=0, column=1, padx=5)
        ttk.Button(btn_frame, text="消费", command=self.show_consume).grid(row=0, column=2, padx=5)
        ttk.Button(btn_frame, text="交易记录", command=self.show_transactions).grid(row=0, column=3, padx=5)

    def load_members(self):
        """加载会员列表"""
        for row in self.tree.get_children():
            self.tree.delete(row)

        cursor = self.conn.cursor()
        cursor.execute("SELECT id, name, phone, balance FROM members")
        for member in cursor.fetchall():
            self.tree.insert('', tk.END, values=member)

    def search_member(self, event=None):
        """搜索会员"""
        query = self.search_entry.get()
        cursor = self.conn.cursor()
        cursor.execute("SELECT id, name, phone, balance FROM members WHERE name LIKE ? OR phone LIKE ?",
                       (f'%{query}%', f'%{query}%'))

        self.tree.delete(*self.tree.get_children())
        for member in cursor.fetchall():
            self.tree.insert('', tk.END, values=member)

    def show_add_member(self):
        """显示添加会员窗口"""
        self.add_window = tk.Toplevel(self.root)
        self.add_window.title("添加新会员")

        ttk.Label(self.add_window, text="姓名:").grid(row=0, column=0, padx=5, pady=5)
        self.name_entry = ttk.Entry(self.add_window)
        self.name_entry.grid(row=0, column=1)

        ttk.Label(self.add_window, text="电话:").grid(row=1, column=0, padx=5, pady=5)
        self.phone_entry = ttk.Entry(self.add_window)
        self.phone_entry.grid(row=1, column=1)

        ttk.Button(self.add_window, text="保存", command=self.save_member).grid(row=2, columnspan=2, pady=10)

    def save_member(self):
        """保存新会员信息"""
        name = self.name_entry.get()
        phone = self.phone_entry.get()

        if not name or not phone:
            messagebox.showerror("错误", "请填写完整信息")
            return

        try:
            cursor = self.conn.cursor()
            cursor.execute("INSERT INTO members (name, phone, reg_date) VALUES (?, ?, ?)",
                           (name, phone, datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
            self.conn.commit()
            self.load_members()
            self.add_window.destroy()
            messagebox.showinfo("成功", "会员添加成功")
        except sqlite3.IntegrityError:
            messagebox.showerror("错误", "该电话号码已存在")

    def show_recharge(self):
        """显示充值窗口"""
        selected = self.tree.focus()
        if not selected:
            messagebox.showerror("错误", "请先选择会员")
            return

        self.recharge_window = tk.Toplevel(self.root)
        self.recharge_window.title("会员充值")

        ttk.Label(self.recharge_window, text="充值金额:").grid(row=0, column=0, padx=5, pady=5)
        self.amount_entry = ttk.Entry(self.recharge_window)
        self.amount_entry.grid(row=0, column=1)

        ttk.Button(self.recharge_window, text="确认充值", command=self.process_recharge).grid(row=1, columnspan=2, pady=10)

    def process_recharge(self):
        """处理充值操作"""
        try:
            amount = float(self.amount_entry.get())
            if amount <= 0:
                raise ValueError
        except:
            messagebox.showerror("错误", "请输入有效的金额")
            return

        selected = self.tree.focus()
        member_id = self.tree.item(selected)['values'][0]

        cursor = self.conn.cursor()
        # 更新余额
        cursor.execute("UPDATE members SET balance = balance + ? WHERE id = ?", (amount, member_id))
        # 记录交易
        cursor.execute("INSERT INTO transactions (member_id, amount, type, description, date) VALUES (?, ?, ?, ?, ?)",
                       (member_id, amount, '充值', '会员卡充值', datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
        self.conn.commit()
        self.load_members()
        self.recharge_window.destroy()
        messagebox.showinfo("成功", f"成功充值{amount}元")

    def show_consume(self):
        """显示消费窗口"""
        selected = self.tree.focus()
        if not selected:
            messagebox.showerror("错误", "请先选择会员")
            return

        self.consume_window = tk.Toplevel(self.root)
        self.consume_window.title("会员消费")

        # 消费项目选择
        ttk.Label(self.consume_window, text="消费项目:").grid(row=0, column=0, padx=5, pady=5)
        self.service_var = tk.StringVar()
        services = ["剪发", "烫发", "染发", "护理", "其他"]
        self.service_menu = ttk.Combobox(self.consume_window, textvariable=self.service_var, values=services)
        self.service_menu.grid(row=0, column=1)

        ttk.Label(self.consume_window, text="消费金额:").grid(row=1, column=0, padx=5, pady=5)
        self.consume_amount = ttk.Entry(self.consume_window)
        self.consume_amount.grid(row=1, column=1)

        ttk.Button(self.consume_window, text="确认消费", command=self.process_consume).grid(row=2, columnspan=2, pady=10)

    def process_consume(self):
        """处理消费操作"""
        try:
            amount = float(self.consume_amount.get())
            if amount <= 0:
                raise ValueError
        except:
            messagebox.showerror("错误", "请输入有效的金额")
            return

        selected = self.tree.focus()
        member_id = self.tree.item(selected)['values'][0]
        current_balance = float(self.tree.item(selected)['values'][3])

        if current_balance < amount:
            messagebox.showerror("错误", "会员余额不足")
            return

        service_type = self.service_var.get() or "其他"

        cursor = self.conn.cursor()
        try:
            # 更新余额和积分（假设消费1元积1分）
            cursor.execute("UPDATE members SET balance = balance - ?, points = points + ? WHERE id = ?",
                           (amount, int(amount), member_id))
            # 记录消费交易
            cursor.execute('''INSERT INTO transactions 
                            (member_id, amount, type, description, date)
                            VALUES (?, ?, ?, ?, ?)''',
                           (member_id, amount, '消费', f'{service_type}服务',
                            datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
            self.conn.commit()

            self.load_members()
            self.consume_window.destroy()
            messagebox.showinfo("成功", f"{service_type}消费{amount}元，剩余积分：{int(amount)}")
        except Exception as e:
            messagebox.showerror("错误", f"操作失败：{str(e)}")

    def show_transactions(self):
        """显示交易记录窗口"""
        selected = self.tree.focus()
        if not selected:
            messagebox.showerror("错误", "请先选择会员")
            return

        member_id = self.tree.item(selected)['values'][0]

        # 创建交易记录窗口
        self.trans_window = tk.Toplevel(self.root)
        self.trans_window.title("交易记录")
        self.trans_window.geometry("600x400")

        # 交易记录表格
        columns = ('日期', '类型', '金额', '描述')
        self.trans_tree = ttk.Treeview(self.trans_window, columns=columns, show='headings')

        # 设置列宽
        col_widths = [150, 80, 80, 200]
        for col, width in zip(columns, col_widths):
            self.trans_tree.heading(col, text=col)
            self.trans_tree.column(col, width=width)

        self.trans_tree.pack(fill=tk.BOTH, expand=True)

        # 添加滚动条
        scrollbar = ttk.Scrollbar(self.trans_window, orient=tk.VERTICAL, command=self.trans_tree.yview)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.trans_tree.configure(yscrollcommand=scrollbar.set)

        # 加载数据
        self.load_transactions(member_id)

    def load_transactions(self, member_id):
        """加载交易记录"""
        for row in self.trans_tree.get_children():
            self.trans_tree.delete(row)

        cursor = self.conn.cursor()
        cursor.execute('''SELECT date, type, amount, description 
                        FROM transactions 
                        WHERE member_id = ?
                        ORDER BY date DESC''', (member_id,))

        for trans in cursor.fetchall():
            # 金额显示添加符号
            amount = trans[2]
            display_amount = f"+{amount}" if trans[1] == '充值' else f"-{amount}"
            self.trans_tree.insert('', tk.END, values=(trans[0], trans[1], display_amount, trans[3]))


if __name__ == "__main__":
    root = tk.Tk()
    app = MembershipSystem(root)
    root.mainloop()